package com.b2s.scrumblr.kb.core.util;

import com.b2s.scrumblr.kb.model.User;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;

/**
 * Created by Administrator on 2016/8/11.
 */
public class ReflectUtil<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectUtil.class);
    public static <T> T setFieldValue(T obj, String fieldName, Object value) throws InvocationTargetException, IllegalAccessException {
        String fieldSetMethodName = "set"+StringUtils.capitalize(fieldName);
        Method[] methods = obj.getClass().getDeclaredMethods();
        if(methods!= null && methods.length > 0){
            for(Method method : methods){
                if(fieldSetMethodName.equals(method.getName())){
                    return (T)method.invoke(obj,value);
                }
            }
        }
        return obj;
    }

    public static Object getFieldValue(Object target, String fieldName){
        String fieldGetMethodName = "get"+StringUtils.capitalize(fieldName);

        try {
            Method method = target.getClass().getDeclaredMethod(fieldGetMethodName);
            return method.invoke(target, null);
        } catch (Exception e) {
            LOGGER.error("get field value fatal:", e);
        }
        return null;
    }

    public static String getKey(Object object){
        if(isPrimitive(object)){
            return object.toString();
        }

        String cacheKey = (String)getFieldValue(object, "cacheKey");
        StringBuilder builder = new StringBuilder(cacheKey).append(":");
        try {
            Method method = object.getClass().getDeclaredMethod("get"+StringUtils.capitalize(cacheKey));
            Object result = method.invoke(object, null);
            builder.append(result);
        } catch (Exception e) {
            LOGGER.error("getKey fatal:", e);
        }
        return builder.toString();
    }

    public static boolean isPrimitive(Object obj){
        boolean result = false;
        try {
            result = ((Class)obj.getClass().getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            //LOGGER.error("isPrimitive fatal:", e);
        }
        return result;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId("1111");
        System.out.println(getKey(111));;
    }
}
